package com.yunzhou.action;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.yunzhou.utils.LogTool;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.InputSource;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.JsonArray;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;


/**
 * @Author xiezw
 * @Date 2024/10/28 20:59
 * @PackageName:com.yunzhou.action
 * @ClassName: aaaaatestAction
 * @Description: LQ01-领料（含低值物料）申请流程TOU8
 * @Version 1.0
 */
public class LQ01Action implements Action {
    private static Log log = LogFactory.getLog(LQ01Action.class.getName());
    private LogTool logTool = new LogTool("/log/huangwm/u8/action/LQ01Action",false);
    @Override
    public String execute(RequestInfo requestInfo) {
        RequestManager rm = null;
        try {
            //获取表单数据id
            rm = requestInfo.getRequestManager();
            int billid = rm.getBillid();//表单数据id
            //获取表单名称
            String tablename = rm.getBillTableName();


            //获取表单主字段信息
            Map<String, String> data = new HashMap<>();
            data.put("requestid", requestInfo.getRequestid());
            Property[] properties = requestInfo.getMainTableInfo().getProperty();
            for (Property property : properties) {
                data.put(property.getName().toLowerCase(), Util.null2String(property.getValue()));
            }
            /*主表字段*/
            //公司编码
            String cCompany = data.get("gsbm");
            //建单日期
            String ddate =data.get("shenqrq");
            //生产订单号：
            String mocode = data.get("scddh");
            //流程编号：
            String processcode = data.get("liucbh");
            //领料类别
            String ll =  data.get("ll");
            //生产订单类型
            String scddlx = data.get("scddlx");
            if(!"19".equals(ll)){
                return SUCCESS;
            }
            if (!"非标准".equals(scddlx)){
                return SUCCESS;
            }
            URL url = new URL("http://10.1.3.16:89/serviceForOA.asmx");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "text/xml");

            // 将主表字段传入json数据
            JsonObject jsonData = new JsonObject();
            JsonObject head = new JsonObject();
            head.addProperty("cCompany", cCompany);
            head.addProperty("ddate", ddate);
            head.addProperty("mocode", mocode);
            head.addProperty("processcode", processcode);
            //获取明细表数据
            JsonArray datalist = new JsonArray();



            //获取明细表数据
            RecordSet rs = new RecordSet();
            rs.execute("select * from " + tablename + "_dt1 where mainid=" + billid);
            while (rs.next()) {
                JsonObject item = new JsonObject();
                //存货编码
                item.addProperty("cinvcode", rs.getString("cinvcode"));
                //数量
                item.addProperty("iquantity", rs.getString("sl"));
                datalist.add(item);

            }
            head.add("datalist", datalist);
            jsonData.add("head", head);


            // 使用 Gson 将 JSON 数据转换为字符串
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String jsonBody = gson.toJson(jsonData);
            logTool.writeLog("我是json的值："+jsonBody);

            // 构建 SOAP 1.2 请求消息体
            String soapXmlRequest = "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                    "<soap:Body>" +
                    "<Addmom_moallocate xmlns=\"http://tempuri.org/\">" +
                    "<strData>"+
                    jsonBody +
                    "</strData>"+
                    "</Addmom_moallocate>" +
                    "</soap:Body>" +
                    "</soap:Envelope>";
            // 发送请求数据
            connection.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(soapXmlRequest);
            writer.flush();
            // 处理响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            writer.close();
            reader.close();
            //将xml中的值获取出来
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new StringReader(response.toString())));

            NodeList nodeList = document.getElementsByTagName("Addmom_moallocateResult");
            if (nodeList.getLength() > 0) {
                Element element = (Element) nodeList.item(0);
                String jsonValue = element.getTextContent().trim();


                // 使用 Gson 解析 JSON 字符串
                JsonArray jsonArray = gson.fromJson(jsonValue, (Type) JsonArray.class);
                // 获取数组中的第一个元素
                JsonObject jsonObject = jsonArray.get(0).getAsJsonObject();
                // 获取 code 和 msg 的值
                String codeValue = jsonObject.get("code").getAsString();
                String msgValue = jsonObject.get("msg").getAsString();


                logTool.writeLog("JSON value: " + jsonValue);
                logTool.writeLog("JSON codeValue: " + codeValue);
                logTool.writeLog("msgValue: " + msgValue);
                if ("0".equals(codeValue)){
                    rm.setMessagecontent("错误提示： " + msgValue);
                    logTool.writeLog("错误提示： " + msgValue);
                    return FAILURE_AND_CONTINUE;
                }
            } else {
              logTool.writeLog("Addmom_moallocateResult element not found in the XML response.");
            }

            // 解析 SOAP 响应
            logTool.writeLog("SOAP Response:");
            logTool.writeLog(response.toString());


        } catch (Exception e) {
            e.printStackTrace();
            rm.setMessagecontent("错误提示： " + e.getMessage());
            return FAILURE_AND_CONTINUE;
        }

        return SUCCESS;
    }
}
